﻿using System.IO;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;
using MicroAmoy.Util.Log;


namespace NePeanRiverService
{
    public class ApiResultAttribute : ActionFilterAttribute
    {
        private Log _logger;
        /// <summary>
        /// 日志操作
        /// </summary>
        public Log Logger
        {
            get { return _logger ?? (_logger = LogFactory.GetLogger(this.GetType().ToString())); }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            #region 记录请求信息
            StringBuilder content = new StringBuilder();
            content.Append(actionExecutedContext.Request.ToString());

            if (!actionExecutedContext.Request.Content.IsMimeMultipartContent())//不含文件
            {
                if (actionExecutedContext.Request.Method == HttpMethod.Post)
                {
                    Stream RrequestStream = actionExecutedContext.Request.Content.ReadAsStreamAsync().Result;
                    RrequestStream.Position = 0;

                    var bytes = new byte[RrequestStream.Length];
                    if (RrequestStream.Length > 0)
                    {
                        RrequestStream.Read(bytes, 0, bytes.Length);
                        RrequestStream.Seek(0, SeekOrigin.Begin);
                    }
                    RrequestStream.Dispose();
                    string str = System.Text.Encoding.UTF8.GetString(bytes);

                    content.Append("\r\nPost内容：" + str);
                }

            }
            _logger.Info("请求内容：" + content.ToString());
            #endregion

            #region 返回结果转为json
            System.Net.Http.ObjectContent respose = (System.Net.Http.ObjectContent)(actionExecutedContext.Response.Content);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(respose == null ? "" : respose.Value.ToString(), Encoding.GetEncoding("UTF-8"), "application/json"), StatusCode = actionExecutedContext.Response.StatusCode };
            base.OnActionExecuted(actionExecutedContext);
            actionExecutedContext.Response = result;
            #endregion
        }
    }
}